package posti.test.swf.service.hibernate;

import java.io.Serializable;

import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import posti.test.swf.dao.Reference;
import posti.test.swf.dao.ReferenceImpl;
import posti.test.swf.service.CRUDService;

public class CRUDServiceHibernateImpl implements CRUDService {
	private SessionFactory sessionFactory;

	public Reference create(Object domainObject) {
		Serializable id = currentSession().save(domainObject);

		return new ReferenceImpl(domainObject.getClass(), id);
	}

	public Object save(Object obj) {
		currentSession().saveOrUpdate(obj);
		return obj;
	}

	public void delete(Object obj) {
		currentSession().delete(obj);
	}

	public Reference reference(Object obj) {
		Serializable id = currentSession().getIdentifier(obj);
		return new ReferenceImpl(obj.getClass(), id);
	}

	public Object retrieve(Reference ref) {
		return currentSession().get(ref.type(), ref.id());
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session currentSession() {
		return sessionFactory.getCurrentSession();
	}
}
